<template>
  <div class="app-container">

    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="110px">
      <el-form-item label="基础管理名称" prop="basicName">
        <el-input v-model="queryParams.basicName" placeholder="请输入基础管理名称" clearable size="small" @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                   v-hasPermi="['biz:risk-type:create']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" icon="el-icon-upload2" size="mini" @click="handleImport">导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" :loading="exportLoading"
                   v-hasPermi="['biz:basic-manage:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 列表 -->
    <el-table v-loading="loading" :data="list">
      <el-table-column label="基础管理名称" align="center" prop="basicName" />
      <el-table-column label="基础管理内容" align="center" prop="basicContent" />
      <el-table-column label="基础管理区域" align="center" prop="basicArea" />
      <el-table-column label="实施单位" align="center" prop="explotUnitName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-document" @click="handleRisk(scope.row)"
                     v-hasPermi="['biz:risk-type:risk']">基础风险</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['biz:basic-manage:update']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['biz:basic-manage:delete']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>

    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="基础管理名称" prop="basicName">
          <el-input v-model="form.basicName" placeholder="请输入基础管理名称" />
        </el-form-item>
        <el-form-item label="基础管理内容" prop="basicContent">
          <el-input v-model="form.basicContent" placeholder="请输入基础管理内容"/>
        </el-form-item>
        <el-form-item label="基础管理区域" prop="basicArea">
          <el-input v-model="form.basicArea" placeholder="请输入基础管理区域" />
        </el-form-item>
        <el-form-item label="实施单位" prop="explotUnit">
          <treeselect v-model="form.explotUnit" :options="checkDeptOptions" :show-count="true"
                      placeholder="请选择所属单位" :normalizer="normalizer"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 风险 -->
    <el-dialog :title="riskTitle" :visible.sync="riskOpen" custom-class="dialogStyle" append-to-body>
      <riskInfo :riskTypeId="riskTypeId" :riskTypeCode="1"></riskInfo>
    </el-dialog>

     <!-- 基础管理导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click='downloadTemplate'>下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { createBasicManage, updateBasicManage, deleteBasicManage, getBasicManage, getBasicManagePage, exportBasicManageExcel, downloadTemplate2 } from "@/api/biz/basicManage";
import riskInfo from "@/views/biz/riskInfo/index"
import { listSimpleDepts } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {getBaseHeader} from "@/utils/request";
export default {
  name: "RiskType",
  components: {
    riskInfo,
    Treeselect
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 基础管理列表
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        basicName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        basicName: [{ required: true, message: "不能为空", trigger: "change" }],
        basicContent: [{ required: true, message: "不能为空", trigger: "change" }],
      },
      // 弹出层标题
      riskTitle: "",
      // 是否显示弹出层
      riskOpen:false,
      riskTypeId:null,
      //实施单位
      checkDeptOptions:undefined,
       // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: getBaseHeader(),
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/admin-api/' + "/biz/basic-manage/import"
      }
    };
  },
  created() {
    this.getList();
    this.getTreeselect();
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true;
      // 处理查询参数
      let params = {...this.queryParams};
      // 执行查询
      getBasicManagePage(params).then(response => {
        this.list = response.list;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        basicName: undefined,
        basicContent: undefined,
        basicArea: undefined,
        explotUnit: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加基础管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      getBasicManage(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改基础管理";
      });
    },
    /** 基础风险按钮操作 */
    handleRisk(row) {
      this.riskTypeId = row.id;
      this.riskOpen = true;
      this.riskTitle = "添加基础风险";
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) {
          return;
        }
        // 修改的提交
        if (this.form.id != null) {
          updateBasicManage(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
          return;
        }
        // 添加的提交
        createBasicManage(this.form).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id;
      this.$modal.confirm('是否确认删除基础管理编号为"' + id + '"的数据项?').then(function() {
          return deleteBasicManage(id);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
    },
     /** 导出按钮操作 */
    handleExport() {
      // 处理查询参数
      let params = {...this.queryParams};
      params.pageNo = undefined;
      params.pageSize = undefined;
      // 执行导出
      this.$modal.confirm('是否确认导出所有基础管理数据项?').then(() => {
          this.exportLoading = true;
          return exportBasicManageExcel(params);
        }).then(response => {
          this.$download.excel(response, '基础管理.xls');
          this.exportLoading = false;
        }).catch(() => {});
    },
     /** 查询部门下拉树结构 + 人员下拉 */
    getTreeselect() {
      listSimpleDepts().then(response => {
        //检查部门
        this.checkDeptOptions = [];
        this.checkDeptOptions.push(...this.handleTree(response.data, "id"));
        //被查部门
        this.checkbyDeptOptions = [];
        this.checkbyDeptOptions.push(...this.handleTree(response.data, "id"));
      });
    },
    // 格式化部门的下拉框
    normalizer(node) {
      return {
        id: node.id,
        label: node.name,
        children: node.children
      }
    },
    /** 下载模板操作 */
    downloadTemplate() {
      downloadTemplate2().then(response => {
        this.$download.excel(response, '基础管理导入模板.xls');
      });
    },
     /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "风险导入";
      this.upload.open = true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      if (response.code !== 0) {
        this.$modal.msgError(response.msg)
        return;
      }
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      // 拼接提示语
      let data = response.data;
      let text = '';
      text += '<br />更新失败数量：' + Object.keys(data.failureBasicnames).length;
      for (const basicname in data.failureBasicnames) {
        text += '<br />&nbsp;&nbsp;&nbsp;&nbsp;' + basicname + '：' + data.failureBasicnames[basicname];
      }
      this.$alert(text, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
  },
};
</script>
<style scoped>
.dialogStyle{
  width:80%;
  height: 80%;
}
</style>
